/* jshint esversion: 6 */
const Router = require('koa-router');
const tool = require("../../tools/tool");
const router = new Router();
const {db, Op, QueryTypes} = require("../../models/db");
// 修改密码

router.post('/user/saveTenant', async ctx => {
    let formData = ctx.request.body.formData
    let mobile = /^1[3-9][0-9]{9}$/.test(formData.mobile)
    if(!mobile) return ctx.err('手机号码不正确')
    // 检测是否有相同手机号
    let c = await db.models['tenant'].count({
        where: {
            mobile: formData.mobile,
        }
    })
    if(c > 0) return ctx.err('已存在相同手机号')
    let a = await db.models['admin'].count({
        where: {
            username: formData.mobile,
        }
    })
    if(a > 0) return ctx.err('已存在相同手机号')
    if(formData.id) {
        db.models['tenant'].update(formData, {
            where: {
                id: formData.id
            }
        })
    }
    else {
        let tenant = await db.transaction(async () => {
            let model = await db.models['tenant'].create(formData, ) // 新增公司
            let admin = {
                tenantId: model.id,
                mobile: formData.mobile,
                username: formData.mobile,
                userpwd: tool.crypto.MD5('121121'),
                token: tool.uuid(),
                name: formData.name,
                pinYin: tool.py(formData.name),
                roleName: '管理员',
                cby: ctx.user.id,
                ctime: tool.getTime()
            }
            await db.models['admin'].create(admin, )
            let sql = `exec to_init_default_data @tenantId=${model.id} `
            await db.query(sql, {type: QueryTypes.UPDATE}, )
            return model
        })
        if(tenant) {
            return  ctx.suc('创建成功')
        }
        return ctx.err('创建失败')
    }
})



module.exports = router;